//
//  ICContactsDetailViewController.m
//  ICome
//
//  Created by zhangrongwu on 16/3/15.
//  Copyright © 2016年 iCom. All rights reserved.
//

#import "ICContactsDetailViewController.h"
#import "ICProfileHeaderView.h"
#import "ICChatViewController.h"
#import "ICUserInfoCell.h"
#import "ICContactItem.h"
#import "ICContactsGroup.h"
#import "ICEmpInfoModel.h"
#import "ICOrganizationViewController.h"
#import "ICMessageDatabase.h"
#import "ICGroup.h"
#import "YYPhotoGroupView.h"
#import <MessageUI/MessageUI.h>
#import <AddressBook/AddressBook.h>
#import "ICSettingArrowItem.h"
#import "ICActionSheetView.h"
#import "ICChatViewController.h"
#import "ICContactsDetailHeaderView.h"
#import "UIImage+AvatarGeneration.h"

@interface ICContactsDetailViewController()<UITableViewDataSource, UITableViewDelegate, MFMessageComposeViewControllerDelegate, ICActionSheetViewDelegate,UINavigationControllerDelegate>
///** 用户lableView */
//@property (nonatomic, strong)ICUserInfoheaderView *userheaderView;
@property (nonatomic, strong)ICContactsDetailHeaderView  *headerView;
/** 头部数据 */
@property (nonatomic, strong)NSDictionary * headerDict;
@property (nonatomic, strong)UIView *footView;
@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong)NSMutableArray *dataList;
@property (nonatomic, strong)ICEmpInfoModel *model;
@property (nonatomic, strong)ICActionSheetView *actionSheet;

@end

@implementation ICContactsDetailViewController

#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    
    if (!self.eId) {
        self.eId = self.parameterDictionary[@"eId"];
    }
    [self setUI];
    [self getData];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self setNav];
}

#pragma mark - UITableViewDelegate
// 设置section高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return 0;
    }
    return 15;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.5;
}

- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *sectionView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, App_Frame_Width, 15)];
    sectionView.backgroundColor = ICRGB(0xefefef);
    return sectionView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 55;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataList.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    ICContactsGroup *group = [self.dataList objectAtIndex:section];
    return group.items.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"ICUserInfoCell";
    ICUserInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[ICUserInfoCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        cell.selectedBackgroundView.layer.backgroundColor = TABLECELLSELECTCOLOR.CGColor;
    }
    cell.titleLabel.textColor = ICRGB(0x333333);
    cell.detailLabel.textColor = ICRGB(0x999999);
    
    cell.titleLabel.font = [UIFont systemFontOfSize:17];
    cell.detailLabel.font = [UIFont systemFontOfSize:17];
    ICContactsGroup *group = [self.dataList objectAtIndex:indexPath.section];
    cell.model = [group.items objectAtIndex:indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    ICContactsGroup *group = [self.dataList objectAtIndex:indexPath.section];
    ICContactItem *Item = [group.items objectAtIndex:indexPath.row];
    
    if ([ICTools regularExpressionWithPhoneNumer:Item.detailTitle]) {
        [ICTools tel:Item.detailTitle];
        return;
    }
    
    if (indexPath.section > 0 && [Item.destVcClass isSubclassOfClass:[ICOrganizationViewController class]]) {
        ICOrganizationViewController *vc = [[ICOrganizationViewController alloc] init];
        vc.titleName = Item.title;
        NSDictionary *dict = self.model.allOrgList[indexPath.section-1];
        vc.oId = dict[@"oId"];
        vc.CtrStyle = CtrStyleOther_sdk;
        [self.navigationController pushViewController:vc animated:YES];
    }
}
#pragma messageDelegate
- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result {
    [self dismissViewControllerAnimated:YES completion:nil];
    if (result == MessageComposeResultCancelled) {
        NSLog(@"Message cancelled");
    } else if (result == MessageComposeResultSent) {
        ALERT(@"短信发送成功");
    } else {
        ALERT(@"短信发送失败");
    }
}

#pragma mark - CustomDelegate
- (void)ActionSheetView:(ICActionSheetView *)actionSheetView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {
        NSString *msg = [NSString stringWithFormat:@"姓名:%@\n手机：%@\n电话：%@\n邮箱：%@\n所在部门：%@\n职位：%@;", self.model.eName, self.model.mobile,self.model.phone,self.model.email,self.model.oName,self.model.jobTitle];
        [self sendSMS:msg recipientList:nil];
    } else if (buttonIndex == 1) {
        [ICContactsDetailViewController CheckAddressBookAuthorization:^(bool isAuthorized) {
            if (isAuthorized) {
                [self creatNewContactToAddressBookWithName:self.model.eName Mobile:self.model.mobile Email:self.model.email];
            } else {
                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"通讯录权限未开启" message:@"未能获得通讯录权限，请您在 系统设置 － 隐私 － 通讯录 中检查" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [alert show];
            }
        }];
    }
}

- (void)videoBtnClick{
    [MBProgressHUD showSuccess:@"敬请期待..."];
}

#pragma mark - event response
- (void)messageBtnClick {
    NSDictionary *param = @{@"eId":[ICUser currentUser].eId,
                            @"eName":[ICUser currentUser].eName,
                            @"otherId":self.model.eId};
    WEAKSELF
    [ICCreateGroupManager createTwoGroupWith:param Handle:^(ICGroup *group) {
        if (group) {
            ICChatViewController *vc = [[ICChatViewController alloc] init];
            vc.group = group;
//            [weakSelf pushMyViewController:vc animated:YES index:2];
            [self.navigationController pushViewController:vc animated:YES];
//            [weakSelf pushToViewController:vc fromViewController:weakSelf animated:YES type:@""];
        }

    }];
}

- (void)postNotification {
    [[NSNotificationCenter defaultCenter] postNotificationName:NotificationDidCreatedConversation object:nil];
}

- (void)rightBtnClick {
//    [self.actionSheet showInView:[ICTools lastWindow].rootViewController.view];
    NSLog(@"self.bounds = %@",self);
//     [self.actionSheet showInView:[ICTools lastWindow].rootViewController.view];
    
    WEAKSELF
    dispatch_async(dispatch_get_main_queue(), ^{
        [weakSelf.actionSheet showInView:[UIApplication sharedApplication].keyWindow];
    });
}

- (void)backClick {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)discoverButtonAction {
    NSLog(@"发现");
}

#pragma mark - private methods
// 设置页面布局
- (void)setUI {
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top);
        make.left.equalTo(self.view.mas_left);
        make.right.equalTo(self.view.mas_right);
        make.bottom.equalTo(self.view.mas_bottom);
    }];
}
// 设置navigation
- (void)setNav {
    [self setNeedsStatusBarAppearanceUpdate];
    [self.navigationController.topViewController preferredStatusBarStyle];
    NSString *userId = [[NSUserDefaults standardUserDefaults] objectForKey:@"user_Id"];
    if([userId isEqualToString:self.eId]){
         self.title = @"我的资料";
    }else{
         self.title = @"详细资料";
    }
    
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem barButtonItemWithImageName:@"App_back_blue" itemType:UIBarButtonItemTypeLeft target:self action:@selector(backClick)];
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem barButtonItemWithImageName:@"App_menubox_blue" itemType:UIBarButtonItemTypeRight target:self action:@selector(rightBtnClick)];
}

// 网络请求
- (void)getData {
    
    //数据处理
    _headerDict = [[NSDictionary alloc]init];
    _headerDict = nil;
    [MBProgressHUD showLoadingActivityView:self.view];
    NSDictionary *param = @{@"eId":self.eId};
    [[ICSocketRequestManager sharedInstance] requestUserInfoWithObject:param Success:^(id object) {
        NSDictionary *dict = [object objectForKey:@"data"];
        self.model = [[ICEmpInfoModel alloc] initWithDict:dict];
        [self reloadData];
        [MBProgressHUD hideLoadingActivityView:self.view];
    } Failure:^(NSError *error, id other) {
        [MBProgressHUD showError:error.domain];
        [MBProgressHUD hideLoadingActivityView:self.view];
    }];
}

// 发送短信
- (void)sendSMS:(NSString *)bodyOfMessage recipientList:(NSArray *)recipients {
    MFMessageComposeViewController *vc = [[MFMessageComposeViewController alloc] init];
    if ([MFMessageComposeViewController canSendText]) {
        vc.body = bodyOfMessage;
        vc.recipients = recipients;
        vc.delegate = self;
        vc.messageComposeDelegate = self;
        [self presentViewController:vc animated:YES completion:^{
            //[vc setNavigationBarHidden:YES animated:YES];
            [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
        }];
    }
}
+(void)CheckAddressBookAuthorization:(void (^)(bool isAuthorized))block
{
    ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, NULL);
    ABAuthorizationStatus authStatus = ABAddressBookGetAuthorizationStatus();
    if (authStatus != kABAuthorizationStatusAuthorized)
    {
        ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error)
                                                 {
                                                     dispatch_async(dispatch_get_main_queue(), ^{
                                                         if (error)
                                                         {
                                                             NSLog(@"Error: %@", (__bridge NSError *)error);
                                                         }
                                                         else if (!granted)
                                                         {
                                                             
                                                             block(NO);
                                                         }
                                                         else
                                                         {
                                                             block(YES);
                                                         }
                                                     });  
                                                 });  
    }
    else
    {
        block(YES);
    }
    
}
// 添加到通讯录
- (void)creatNewContactToAddressBookWithName:(NSString *)name Mobile:(NSString *)mobile Email:(NSString *)email
{   CFErrorRef error = NULL;
    ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, &error);
    ABRecordRef newRecord = ABPersonCreate();
    if(name !=nil){
    ABRecordSetValue(newRecord, kABPersonFirstNameProperty, (__bridge CFTypeRef)name, &error);
    }
    ABMutableMultiValueRef multi = ABMultiValueCreateMutable(kABMultiStringPropertyType);
    if(mobile !=nil){
    ABMultiValueAddValueAndLabel(multi, (__bridge CFTypeRef)mobile, kABPersonPhoneMobileLabel, NULL);
    }
    ABRecordSetValue(newRecord, kABPersonPhoneProperty, multi, &error);
    ABMutableMultiValueRef multiEmail = ABMultiValueCreateMutable(kABMultiStringPropertyType);
     if(email !=nil){
    ABMultiValueAddValueAndLabel(multiEmail, (__bridge CFTypeRef)(email), kABWorkLabel, NULL);
     }
    ABRecordSetValue(newRecord, kABPersonEmailProperty, multiEmail, &error);
    ABAddressBookAddRecord(addressBook, newRecord, &error);
    ABAddressBookSave(addressBook, &error);
    ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
        if (granted) {
            UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"添加成功" message:nil preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                [self dismissViewControllerAnimated:YES completion:nil];
            }];
            [alertVc addAction:alertAction];
            [self presentViewController:alertVc animated:YES completion:nil];
        }
    });
    CFRelease(multiEmail);
    CFRelease(multi);
    CFRelease(newRecord);
    CFRelease(addressBook);
}

- (void)reloadData {
    _headerView.hidden = NO;
    _footView.hidden   = NO;
    
    NSString *URL = [ICTools getMaxImageURL:(self.model.photoId)];
    [UIImage addAvatariamgeView:self.headerView.headImageView withUrlStr:URL witheId:self.model.eId withName:self.model.eName];
    
    
    self.headerView.titleLabel.text = self.model.eName;
//    self.headerView.jobLabel.text = self.model.jobTitle;
    self.headerView.nameLabel.text = self.model.account;
    
    if (self.dataList.count > 0) {
        [self.dataList removeAllObjects];
    }
    //ICContactItem *company = [ICContactItem itemWithIcon:@"" title:NSLocalizedString(@"userOrganization", nil) detailTitle:self.model.companyName destVcClass:nil];
    ICContactItem *mobileTel = [ICContactItem itemWithIcon:@"App_rightArrow" title:@"手机" detailTitle:self.model.mobile destVcClass:nil];
    ICContactItem *tel = [ICContactItem itemWithIcon:@"App_rightArrow" title:@"电话" detailTitle:self.model.phone destVcClass:nil];
    ICContactItem *email = [ICContactItem itemWithIcon:@"" title:@"邮箱" detailTitle:self.model.email destVcClass:nil];
    
    ICContactsGroup *baseGroup = [[ICContactsGroup alloc] init];
    NSMutableArray *sectionList = [[NSMutableArray alloc] init];
//    [sectionList addObject:company];
    [sectionList addObject:mobileTel];
    if (![ICTools stringEmpty:self.model.phone]) { // 电话不为空时添加
        [sectionList addObject:tel];
    }
    if (![ICTools stringEmpty:self.model.email]) {
        [sectionList addObject:email];
    }
    baseGroup.items = [sectionList copy];
    [_dataList addObject:baseGroup];
    int index = 0;
    for (NSDictionary *dict in self.model.allOrgList) {
        ICContactsGroup *addGroup = [[ICContactsGroup alloc] init];
        NSMutableArray *jobSectionList = [[NSMutableArray alloc] init];
        if (index == 0) {
            ICContactItem *unit = [ICContactItem itemWithIcon:@"App_rightArrow" title:@"单位" detailTitle:dict[@"oLongName"] destVcClass:[ICOrganizationViewController class]];
            [jobSectionList addObject:unit];
            ICContactItem *organize = [ICContactItem itemWithIcon:@"App_rightArrow" title:@"组织" detailTitle:dict[@"oName"] destVcClass:[ICOrganizationViewController class]];
            [jobSectionList addObject:organize];
            ICContactItem *job = [ICContactItem itemWithIcon:@"" title:@"职位" detailTitle:dict[@"jobTitle"] destVcClass:nil];
            [jobSectionList addObject:job];
            
            addGroup.items = [jobSectionList copy];
            [_dataList addObject:addGroup];
        } else {
            ICContactItem *unit = [ICContactItem itemWithIcon:@"App_rightArrow" title:@"单位" detailTitle:dict[@"oLongName"] destVcClass:[ICOrganizationViewController class]];
            [jobSectionList addObject:unit];
            ICContactItem *organize = [ICContactItem itemWithIcon:@"App_rightArrow" title:@"组织" detailTitle:dict[@"oName"] destVcClass:[ICOrganizationViewController class]];
            [jobSectionList addObject:organize];
            ICContactItem *job = [ICContactItem itemWithIcon:@"" title:@"职位" detailTitle:dict[@"jobTitle"] destVcClass:nil];
            [jobSectionList addObject:job];
            
            addGroup.items = [jobSectionList copy];
            [_dataList addObject:addGroup];
        }
        index++;
    }
    
    [self.tableView reloadData];
}

#pragma mark - getters and setters
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, App_Frame_Width, APP_Frame_Height) style:UITableViewStyleGrouped];
        //UITableViewStylePlain
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.userInteractionEnabled = YES;
        _tableView.backgroundColor = [UIColor whiteColor];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.tableHeaderView = self.headerView;
        
        
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        } else {
            self.automaticallyAdjustsScrollViewInsets = NO;
        }
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        
        [self.view addSubview:_tableView];
    }
    return _tableView;
}

-(ICContactsDetailHeaderView *)headerView
{
    if(!_headerView)
    {
        _headerView = [[ICContactsDetailHeaderView alloc] initWithFrame:CGRectMake(0, 0, App_Frame_Width, App_Frame_Width/375.0f * 80)];
        _headerView.hidden = YES;
        _headerView.backgroundColor = [UIColor clearColor];
        _headerView.layer.shadowColor = ICRGB(0xdddddd).CGColor;
        _headerView.layer.shadowOffset = CGSizeMake(0, 5);//shadowOffset阴影偏移，默认(0, -3),这个跟shadowRadius配合使用
        _headerView.layer.shadowOpacity=0.5;//阴影透明度，默认0
        _headerView.layer.shadowRadius=5;//阴影半径，默认3
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithActionBlock:^(id  _Nonnull sender) {
            UIView *fromView = nil;
            NSMutableArray *items = [[NSMutableArray alloc] init];
            YYPhotoGroupItem *item = [YYPhotoGroupItem new];
            item.thumbView = _headerView.headImageView;
            NSString *URL = [ICTools getOglImageURL:(self.model.photoId)];
            item.largeImageURL = [NSURL URLWithString:URL];
            [items addObject:item];
            fromView = _headerView.headImageView;
            YYPhotoGroupView *v = [[YYPhotoGroupView alloc] initWithGroupItems:items];
            [v presentFromImageView:fromView toContainer:self.navigationController.view fromViewC:self animated:YES completion:nil];
        }];
        
        //_userheaderView.bgImageView.image = [UIImage imageNamed:@"icon_userinfo_bg"];
//        [_headerView.discoverButton setImage:[UIImage imageNamed:@"icon_userinfo_discover"] forState:UIControlStateNormal];
//        [_headerView.discoverButton addTarget:self action:@selector(discoverButtonAction) forControlEvents:UIControlEventTouchUpInside];
        
//        [_headerView.sendIMButton setImage:[UIImage imageNamed:@"icon_userinfo_send"] forState:UIControlStateNormal];
        [_headerView.sendIMButton addTarget:self action:@selector(messageBtnClick) forControlEvents:UIControlEventTouchUpInside];
        
//        [_headerView.videoCallButton setImage:[UIImage imageNamed:@"icon_userinfo_video"] forState:UIControlStateNormal];
//        [_headerView.videoCallButton addTarget:self action:@selector(videoBtnClick) forControlEvents:UIControlEventTouchUpInside];
        
        [_headerView.headImageView addGestureRecognizer:tap];

    }
    return _headerView;
}



-(UIView *)footView {
    if (!_footView) {
        _footView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, App_Frame_Width, 150)];
        _footView.hidden = YES;
        UIButton *btn = [[UIButton alloc] init];
        btn.frame = CGRectMake(10, 55, App_Frame_Width - 2 * 10, 50 * Level);
        [btn setTitle:@"发消息" forState:UIControlStateNormal];
        [btn setBackgroundImage:[UIImage imageNamedFromiComeSDKBundle:@"icon_detail_sender"] forState:UIControlStateNormal];
        btn.titleLabel.font = ICBOLDFont(17 * Level);
        btn.layer.cornerRadius = 5;
        [btn addTarget:self action:@selector(messageBtnClick) forControlEvents:UIControlEventTouchUpInside];
        [_footView addSubview:btn];
        
    }
    
    return _footView;
}

-(ICActionSheetView *)actionSheet {
    if (!_actionSheet) {
        _actionSheet = [[ICActionSheetView alloc] initWithTitles:@[@"发送名片",@"保存到手机通讯录"] delegate:self cancelButtonTitle:@"取消"];
    }
    return _actionSheet;
}

- (NSMutableArray *)dataList {
    if (!_dataList) {
        _dataList = [[NSMutableArray alloc] init];
    }
    return _dataList;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    CGPoint point = scrollView.contentOffset;
    
    if (point.y <= 0) {
        
        self.tableView.contentOffset = CGPointMake(0.0, 0.0);
        
    }
    
}

#pragma mark -
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    MFMessageComposeViewController *vc = (MFMessageComposeViewController *)navigationController;
    [vc setNavigationBarHidden:YES animated:YES];
}
@end
